package com.byzk.invoice.util;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

/**
 * 文本操作工具类.
 *
 * @author 康鹏 2020-05-20
 */
public class DocumentUtil {

    /**
     * 将文本写入指定目录下.
     *
     * @param document 文本内容
     * @param xmlPath  指定xml文件路径
     * @param isFormat 是否格式化
     * @throws Exception Exception
     */
    public static void writer(Document document, String xmlPath, boolean isFormat) throws Exception {

        File file = new File(xmlPath);
        File parentFile = file.getParentFile();
        if (!file.exists()) {
            parentFile.mkdirs();
            file.createNewFile();
        }

        if (isFormat) {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            format.setNewLineAfterDeclaration(false);
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), format);
            writer.write(document);
            writer.flush();
            writer.close();
        } else {
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
            writer.write(document);
            writer.flush();
            writer.close();
        }
    }

}
